import React from 'react';
import { Row, Col, Checkbox } from 'antd';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import memoizeOne from 'memoize-one';
import { InputSpecifiedProps, InputSpecifiedState } from '../data';

const weekOptions = {
  MON: '星期一',
  TUE: '星期二',
  WED: '星期三',
  THU: '星期四',
  FRI: '星期五',
  SAT: '星期六',
  SUN: '星期日',
} as const;

/**
 * cron时间表达式生成器-周面板
 * 属性如下：
 */
class InputSpecified extends React.PureComponent<InputSpecifiedProps, InputSpecifiedState> {

  state: InputSpecifiedState = {
    selected: []
  }

  /**
   * 静态函数，根据新传入的props来映射到state。
   * 该函数必须有返回值。当props传入的内容不需要影响state，就必须返回一个null
   */
  static getDerivedStateFromProps(nextProps: InputSpecifiedProps, prevState: InputSpecifiedState) {
    // console.log('InputFromTo.getDerivedStateFromProps: ', nextProps, prevState);
    // 重新查询清空表格勾选
    const { disabled } = nextProps;
    if (disabled) {
      return {
        selected: []
      };
    }
    return null;
  }

  /**
   * 创建多选框集合
   * @param {*} weekOptions 星期集合
   * @param {*} disabled 栏位是否可用
   * @returns 多选框集合
   */
  createCheckbox = (disabled: boolean) => {
    console.log('周createCheckbox');
    return Object.entries(weekOptions).map(([weekCode, weekName]) => {
      return (
        <Col key={weekCode}>
          <Checkbox disabled={disabled} value={weekCode}>
            {weekName}
          </Checkbox>
        </Col>
      );
    });
  }
  // 生成可缓存的方法，当disabled不变时，不计算直接返回上一次的结果
  memoizedCreateCheckbox = memoizeOne(this.createCheckbox);

  onChangeSelected = (value: Array<CheckboxValueType>) => {
    const { onChange } = this.props;
    // 当没有勾选时，默认选中0
    if (onChange) {
      onChange(value.length === 0 ? 'MON' : value.join(','));
    }
  }

  render() {
    const { disabled, value } = this.props;
    let { selected } = this.state;
    console.log(selected, value);
    if (!disabled && value) {
      selected = value.split(',');
      console.log('周指定', selected, value);
    }
    const checkList = this.memoizedCreateCheckbox(disabled);

    return (
      <React.Fragment>
        指定
        <br />
        <Checkbox.Group style={{ width: '100%' }} value={selected} onChange={this.onChangeSelected}>
            <Row>{checkList}</Row>
        </Checkbox.Group>
      </React.Fragment>
    );
  }
}

export default InputSpecified;